import { Router } from 'express'
import PermissionDao from '../dao/PermissionDao.js'
import Permission from '../verify/Permission.js'

let router = Router()

router.route('/api/permission')
    .post(async (req, res) => {
        let permission = Permission.insertObj(req.body)
        if (!permission) return res.end(JSON.stringify({ code: 500, msg: '参数有误' }))

        let result = await PermissionDao.insert(permission)
        if (result instanceof Error) return res.end(JSON.stringify({ code: 500, msg: '数据库操作失败' }))

        return res.end(JSON.stringify({ code: 200 }))
    })

    .delete(async (req, res) => {
        let permission = Permission.deleteObj(req.body)
        if (!permission) return res.end(JSON.stringify({ code: 500, msg: '参数有误' }))

        let result = await PermissionDao.delete(permission)
        if (result instanceof Error) return res.end(JSON.stringify({ code: 500, msg: '数据库操作失败' }))

        return res.end(JSON.stringify({ code: 200 }))
    })

    .put(async (req, res) => {
        let permission = Permission.updateObj(req.body)
        if (!permission) return res.end(JSON.stringify({ code: 500, msg: '参数有误' }))

        let result = await PermissionDao.update(permission)
        if (result instanceof Error) return res.end(JSON.stringify({ code: 500, msg: '数据库操作失败' }))

        return res.end(JSON.stringify({ code: 200 }))
    })

router
    .get('/api/permission/:id', async (req, res) => {
        let result = await PermissionDao.selectById(req.params.id)
        if (result instanceof Error) return res.end(JSON.stringify({ code: 500, msg: '数据库操作失败' }))

        return res.end(JSON.stringify({ code: 200, data: result }))
    })

    .get('/api/permissionByPage/:pageIndex/:pageSize', async (req, res) => {
        let { pageIndex, pageSize } = req.params

        let result = await PermissionDao.selectByLimit((pageIndex - 1) * pageSize, pageSize)
        if (result instanceof Error) return res.end(JSON.stringify({ code: 500, msg: '数据库操作失败' }))

        return res.end(JSON.stringify({ code: 200, data: result }))
    })

    .get('/api/permissionTotal', async (req, res) => {
        let result = await PermissionDao.selectCount()
        if (result instanceof Error) return res.end(JSON.stringify({ code: 500, msg: '数据库操作失败' }))

        return res.end(JSON.stringify({ code: 200, data: result }))
    })

    .get('/api/permissionByRoleId/:role_id', async (req, res) => {
        let result = await PermissionDao.selectByRoleId(req.params.role_id)
        if (result instanceof Error) return res.end(JSON.stringify({ code: 500, msg: '数据库操作失败' }))

        return res.end(JSON.stringify({ code: 200, data: result }))
    })

export default router